package com.xxrl.shop.service;

import com.xxrl.shop.domain.User;
import com.xxrl.shop.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;


/**
 * @author mis
 */
@Service
public class UserService {
    private final UserRepository userRepository;

    @Autowired
    public UserService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @CacheEvict(cacheNames = "homePageStatistics")
    public void saveUser(User user) {
        userRepository.save(user);
    }

    public void removeUser(Long id) {
        userRepository.deleteById(id);
    }

    public User getUserById(Long id) {
        return userRepository.getOne(id);
    }

    public User getUserByName(String name) {
        return  userRepository.queryByName(name);
    }

    public Page<User> findAll(Pageable pageable) {
        return userRepository.findAll(pageable);
    }

    public List<String> getPermissionByRole(String role) {
        List<String> permissions = new ArrayList<>();
        permissions.add(role);
        return permissions;
    }

    public boolean userExist(User user) {
        return userRepository.existsUserByEmailOrPhoneOrName(user.getEmail(),user.getPhone(),user.getName());
    }

    public boolean emailInUse(String email) {
        return userRepository.existsByEmail(email);
    }

    public boolean phoneInUse(String phone) {
        return userRepository.existsByPhone(phone);
    }

    public int countUser() {
        return (int) userRepository.count();
    }
}
